import { useState, useEffect } from 'react'
import './index.scss'
const Time = () => {
  const [years, setYears] = useState(0)
  const [months, setMonths] = useState(0)
  const [days, setDays] = useState(0)
  const [hours, setHours] = useState(0)
  const [minutes, setMinutes] = useState(0)
  const [seconds, setSeconds] = useState(0)
  const [intervalValue, setIntervalValue] = useState<any>()
  // 你的出生日期
  const birthDate = new Date('1994-12-20')
  // 计算退休日期（60 岁）
  const retirementDate: any = new Date(birthDate)
  retirementDate.setFullYear(birthDate.getFullYear() + 60)
  // 更新倒计时
  function updateCountdown() {
    const now: any = new Date() // 当前时间
    const timeRemaining = retirementDate - now // 剩余时间（毫秒）
    // 如果已经退休
    if (timeRemaining <= 0) {
      console.log('恭喜你，已经退休了！')
      clearInterval(intervalValue)
      return
    }

    // 计算剩余的年、月、日、时、分、秒
    const years = Math.floor(timeRemaining / (1000 * 60 * 60 * 24 * 365))
    const months = Math.floor(
      (timeRemaining % (1000 * 60 * 60 * 24 * 365)) / (1000 * 60 * 60 * 24 * 30)
    )
    const days = Math.floor(
      (timeRemaining % (1000 * 60 * 60 * 24 * 30)) / (1000 * 60 * 60 * 24)
    )
    const hours = Math.floor(
      (timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
    )
    const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60))
    const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000)

    // 输出倒计时
    setYears(years)
    setMonths(months)
    setDays(days)
    setHours(hours)
    setMinutes(minutes)
    setSeconds(seconds)
    // console.log(
    //   `距离退休还有：${years} 年 ${months} 月 ${days} 日 ${hours} 时 ${minutes} 分 ${seconds} 秒`
    // )
  }
  useEffect(() => {
    // 每秒更新一次倒计时
    const interval = setInterval(() => {
      clearInterval(interval)
      updateCountdown()
    }, 1000)
    setIntervalValue(interval)
  }, [seconds])
  return (
    <div className="backBox">
      <div className="box">
        <div id="YY">{years}</div>
        <div>年</div>
        <div id="MM">{months}</div>
        <div>月</div>
        <div id="DD">{days}</div>
        <div style={{ marginRight: 5 }}>日</div>
        <div id="HH">{hours}</div>
        <div>时</div>
        <div id="mm">{minutes}</div>
        <div>分</div>
        <div id="ss">{seconds}</div>
        <div>秒</div>
      </div>
    </div>
  )
}
export default Time
